import logging
import os
from logging.handlers import TimedRotatingFileHandler
from config import LOG_DIR # 导入日志目录配置

# 获取根logger
logger = logging.getLogger()

def setup_logging():
    """配置全局日志记录器"""
    logger.setLevel(logging.INFO)  # 设置全局日志级别为INFO

    # 移除所有默认的处理器 (避免重复日志输出)
    for handler in logger.handlers[:]:
        logger.removeHandler(handler)

    # 控制台日志处理器配置
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

    # 文件日志处理器配置 - 每天午夜轮转
    os.makedirs(LOG_DIR, exist_ok=True) # 确保日志目录存在
    log_file_path = os.path.join(LOG_DIR, "app.log")
    file_handler = TimedRotatingFileHandler(
        log_file_path, when="midnight", interval=1, backupCount=30, encoding='utf-8'
    )
    file_handler.suffix = "%Y-%m-%d.log"  # 设置轮转日志文件后缀格式
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    logging.info("日志系统初始化完成。") 